﻿using System;
using System.ComponentModel;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using EDMDesigner.Designer.Controls.Mapping.Resources;
using EDMDesigner.Designer.Controls.Util;

namespace EDMDesigner.Designer.Controls.Mapping
{
    public abstract partial class ColumnComboBox : UserControl
    {
        public ColumnComboBox()
        {
            InitializeComponent();
            columnNullValues.Collection = NullValue.GetValues(NullValueText);
        }

        protected virtual string NullValueText
        {
            get { return MappingResources.NullValueNone; }
        }

        private ComboBoxSelectedValueBindingWithNull<Business.SSDL.Property.Property> _columnComboBoxValue;
        public ComboBoxSelectedValueBindingWithNull<Business.SSDL.Property.Property> ColumnComboBoxValue
        {
            get
            {
                if (_columnComboBoxValue == null)
                    _columnComboBoxValue = new ComboBoxSelectedValueBindingWithNull<Business.SSDL.Property.Property>(Column, column => OnColumnComboBoxValueChanged(column));
                return _columnComboBoxValue;
            }
        }

        protected abstract void OnColumnComboBoxValueChanged(Business.SSDL.Property.Property column);

        public EDMDesigner.Business.SSDL.EntityType.EntityType Table
        {
            get { return (Business.SSDL.EntityType.EntityType)GetValue(TableProperty); }
            set { SetValue(TableProperty, value); }
        }
        public static readonly DependencyProperty TableProperty =
            DependencyProperty.Register("Table", typeof(Business.SSDL.EntityType.EntityType), typeof(ColumnComboBox), new UIPropertyMetadata(null,
                (sender, e) =>
                {
                    var columnMapping = (ColumnComboBox)sender;
                    columnMapping.columns.Collection = ((Business.SSDL.EntityType.EntityType)e.NewValue).Properties;
                    columnMapping.columnComboBox.GetBindingExpression(ComboBoxEditableWhenFocused.SelectedValueProperty).UpdateTarget();
                }));

        public EDMDesigner.Business.SSDL.Property.Property Column
        {
            get { return (Business.SSDL.Property.Property)GetValue(ColumnProperty); }
            set { SetValue(ColumnProperty, value); }
        }
        public static readonly DependencyProperty ColumnProperty =
            DependencyProperty.Register("Column", typeof(Business.SSDL.Property.Property), typeof(ColumnComboBox), new UIPropertyMetadata(null,
                (sender, e) =>
                {
                    var columnMapping = (ColumnComboBox)sender;
                    columnMapping._columnComboBoxValue = null;
                    columnMapping.columnComboBox.GetBindingExpression(ComboBoxEditableWhenFocused.SelectedValueProperty).UpdateTarget();
                }));
    }
}
